package web.controller;

import web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService service;
    /*
     * 分页查询数据，访问地址：http;//localhost:8080/user/list
     *
     * @param page 页码数
     **/

    @ResponseBody
    @RequestMapping("list")
    public Map<String, Object> list(Integer page, Integer size) {
        return service.list(page, size);
    }

    // 访问地址 http;//localhost:8080/check
    @RequestMapping("check")
    @ResponseBody
    public Long check(String username, String password, HttpServletRequest request) {
        Long id = service.checkUsernameAndPassword(username, password);
        HttpSession session = request.getSession();
        if (id != null && id > 0) {
            session.setAttribute("UID", id);
        }
        return id;
    }

    @RequestMapping("registerCheck")
    @ResponseBody
    public Integer register(String username, String name, HttpServletRequest request) {
        return service.register(username, name);
    }

    @RequestMapping("modifyUser")
    @ResponseBody
    public boolean modifyUser(String name, String password, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Long id = (Long) session.getAttribute("UID");
        System.out.println(id);
        System.out.println(name);
        System.out.println(password);
        return service.modifyUserNameAndPassword(id, name, password);
    }

    @RequestMapping("login")
    public String loginPage() {
        return "login";
    }

    @RequestMapping("register")
    public String registerPage() {
        return "register";
    }

    @ResponseBody
    @RequestMapping("disableUser")
    public boolean disableUser(Long id) {
        return service.disableUser(id);
    }

    @ResponseBody
    @RequestMapping("enableUser")
    public boolean enableUser(Long id) {
        return service.enableUser(id);
    }

    @ResponseBody
    @RequestMapping("deleteUser")
    public boolean deleteUser(Long id) {
        return service.deleteUser(id);
    }
}
